package evs.indices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import evs.location.EvsException;
import evs.security.SecureServlet;

public class IndexServlet extends SecureServlet
{
    private static final long serialVersionUID = 4949553336283575237L;
    private String _locations;
    
    @Override
    public void init() throws ServletException
    {
        super.init();
        
        String configFilePath = this.getInitParameter("index-config-file");
    
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream( configFilePath );
        
        if ( stream == null )
        {
            throw new ServletException( "Could not find configuration file for IndexServlet!" );
        }
        
        try
        {
            BufferedReader reader = new BufferedReader( new InputStreamReader( stream ) );
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ( ( line = reader.readLine() ) != null )
            {
                sb.append( line );
                sb.append( '\n' );
            }
            
            _locations = sb.toString();
        }
        catch ( IOException e )
        {
            throw new ServletException( e );
        }
        finally
        {
            if ( stream != null )
            {
                try
                {
                    stream.close();
                }
                catch ( IOException e )
                {    
                }
            }
        }
    }

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
                    throws ServletException, IOException
    {
        try
        {
            _checkAllowRequest( request );
            
            response.getWriter().write( _locations );
        } 
        catch ( EvsException e )
        {
            response.sendError( e.HTTP_CODE, e.getMessage() );
        }
    }
  
    @Override
    protected boolean _allowOnlyLocalAccess()
    {
        return true;
    }
}
